#include "DynamicBrick.h"
#include "Resource.h"

DynamicBrick::DynamicBrick(LPDIRECT3DDEVICE9 d3ddv,  LPDIRECT3DSURFACE9 backBuffer, LPD3DXSPRITE spriteHandler, float x, float y, int ID, int Object_State) : Object(x, y)
{
	this->setIDObjType(ID);
	 
	p_sprite = new Sprite(spriteHandler, ResourceMng::GetInst(d3ddv, backBuffer)->GetTexture(ResourceMng::GetInst(d3ddv, backBuffer)->getMapTexture()[50]->getFileName()), 0, 0);
	 
	width = p_sprite->getTexture()->getWidth();
	height = p_sprite->getTexture()->getHeight();

	veloc_x = DYNAMIC_BRICK_VX;
	this->obj_state = Object_State;
}

DynamicBrick::~DynamicBrick()
{
	if (p_sprite)
	{
		delete p_sprite;
	}
}

void DynamicBrick::update(list<Object*>* obj_list, DxInput* input, float TPF)
{
	//Object::update(obj_list, input, TPF);
	width = p_sprite->getTexture()->getWidth();
	height = p_sprite->getTexture()->getHeight();

	pos_x_old = pos_x;
	pos_y_old = pos_y;

	pos_x += veloc_x * TPF;

	Object* obj;
	list<Object*>::iterator i_obj;
	for (i_obj = obj_list->begin(); i_obj != obj_list->end(); i_obj++)
	{
		obj = *i_obj;
		Box box(this->pos_x_old,
			this->pos_y_old - this->height, 
			width, 
			height, 
			veloc_x * TPF, 
			0);

		Box block(obj->getPosX(),
			obj->getPosY() - obj->getHeight(),
			obj->getWidth(),
			obj->getHeight());

		Box boxphase = Collision::GetSweptBroadphaseBox(box);
		if (Collision::AABBCheck(boxphase, block))
		{
			float normalx = 0;
			float normaly = 0;
			float collision_time = Collision::SweptAABB(box, block, normalx, normaly);
			if (0 < collision_time && collision_time < 1)
			{
				if (obj->getObjectType() == OBJECT_LAND)
				{
					pos_x = pos_x_old;
					veloc_x = -veloc_x;
				}
			}


		}//end if
	}//end for

	pos_x_old = pos_x;
	pos_y_old = pos_y;

	p_sprite->update(TPF);
}

void DynamicBrick::render(int cameraX, int cameraY)
{
	Object::render(cameraX, cameraY);
}

OBJECT_TYPE DynamicBrick::getObjectType()
{
	return OBJECT_LAND;
}